#!/bin/env python

'''
python 3.5.2
benjamin
'''

from urllib3 import ProxyManager, make_headers, PoolManager
import os
import re
from xml.dom.minidom import parse, parseString
import time
import json

def nodeAttribute(id, xml, attr, index=0):
    dom = parseString(xml)
    e = dom.getElementById(id)
    rst = e.__getattribute__(attr)
    return rst

def nodeAttrFormXml(nodeName, xmlStr, attr, index=0, nodeId=None):
    # indexStart = xmlStr.index('<%s>'%nodeName, index)+len(nodeName)+2
    # indexEnd = xmlStr.index('</%s>'%nodeName, index)

    # xmlStr[indexStart,indexEnd]
    match = re.finditer(r'<%s[^<>]*(?= />|</%s>)'%(nodeName, nodeName), xmlStr)
    tNode = next(match).group(index)
    print('macth node string: '+tNode)
    for a in tNode.split():
        akv = a.strip().split('=')
        if len(akv) > 1:
            if akv[0] == attr:
                return akv[1].strip('"')
    return 

def saveBgImage(http, imgHref, saveFold):
    imgName = '1.jpg' #os.path.basename(imgHref)
    splitHref = re.split(r'(\?|&|=)', imgHref)
    # splitHref.reverse()
    for i in splitHref:
        if i.lower().endswith('.jpg') or i.lower().endswith('.png'):
            imgName = i
            break

    fullImgName = os.path.abspath(saveFold+imgName)
    print('ready to save image %s'%fullImgName)
    if os.path.exists(fullImgName):
        print('skip %s'%fullImgName)
        return -1

    img_req = http.request('GET', 'https://cn.bing.com'+imgHref)
    
    file = open(fullImgName, 'wb')
    file.write(img_req.data)
    file.close()
    
    return 0

def catchBgImage(saveFold='./bgImages/'):
    # os.system("source ~/.bash_profile")
    # try:
    #     os.environ['HOME']
    # except KeyError as identifier:
    #     exit()
    # proxyInfo = []
    if 'http_proxy' in os.environ:
        proxyInfo = re.split('(://|@)', os.environ['http_proxy']) # throw KeyError if no http_proxy in env
    # ['http', '://', 'username:password', '@', '10.191.131.14:3128']
        
    else:
        proxyInfo = ['http', '://', 'F1218975:1qaz2wsxS00', '@', '10.191.131.14:3128']
    
    c_proxy_headers = make_headers(proxy_basic_auth=proxyInfo[2])
    # print(c_proxy_headers)
    http = ProxyManager('%s://%s'%(proxyInfo[0], proxyInfo[4]), proxy_headers=c_proxy_headers)
    # print(http.proxy)
    # print(http.proxy_headers)
    # Now you can use `http` as you would a normal PoolManager
    r = http.request('GET', 'https://cn.bing.com/')
    # print(r.data)
    imgHref = nodeAttrFormXml('link', r.data.decode("utf-8"), 'href')
    # print(imgHref)
    time.sleep(1)
    saveBgImage(http, imgHref, saveFold)
    sh_igl_disabled = nodeAttribute('sh_igl', r.data.decode("utf-8"), 'aria-disabled')
    i=0
    while sh_igl_disabled==None or sh_igl_disabled!='true':
        r = http.request('GET', 'https://cn.bing.com/')
        file = open(saveFold+i+".png", 'wb')
        file.write(r.data)
        file.close()
        # saveBgImage(http, imgHref, saveFold)
        sh_igl_disabled = nodeAttribute('sh_igl', r.data, 'aria-disabled')
    
    return 0

def catchBgImage2(saveFold='./'):
    if 'http_proxy' in os.environ:
        proxyInfo = re.split('(://|@)', os.environ['http_proxy']) # throw KeyError if no http_proxy in env
    # ['http', '://', 'username:password', '@', '10.191.131.14:3128']
        
    else:
        proxyInfo = ['http', '://', 'F1218975:1qaz2wsxS00', '@', '10.191.131.14:3128']
    
    # c_proxy_headers = make_headers(proxy_basic_auth=proxyInfo[2])
    # print(c_proxy_headers)

    # no proxy
    # http = ProxyManager('%s://%s'%(proxyInfo[0], proxyInfo[4]), proxy_headers=c_proxy_headers)
    http = PoolManager()

    # fields={'format':'js','idx':0,'n':1,'nc':1550193900669,'pid':'hp'}
    r = http.request('GET', 'https://cn.bing.com/HPImageArchive.aspx', fields={'format':'js','idx':0,'n':10,'pid':'hp'})
    # print(r.data.decode("utf-8"))
    imageInfo = json.loads(r.data.decode("utf-8"))
    # print(imageInfo)
    for i in imageInfo['images']:
        # print(i['url'])
        saveBgImage(http, i['url'], saveFold)
        # break

if __name__=='__main__':
    saveFold='./bgImages/'
    if not os.path.exists(saveFold):
        os.makedirs(os.path.abspath(saveFold))
    if os.name == 'nt':
        saveFold = '.\\bgImages\\'
    catchBgImage2(saveFold)
